<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<meta content="yes" name="apple-mobile-web-app-capable" />
<meta content="black" name="apple-mobile-web-app-status-bar-style" />
<meta content="telephone=no" name="format-detection" />
<meta content="email=no" name="format-detection" />
<title>巡检-连接设备</title>
		<link rel="stylesheet" href="../../css/s_plus.css" />
		<link rel="stylesheet" href="../../css/base.css" />
		<link rel="stylesheet" href="../../css/layout.css" />
		<link rel="stylesheet" href="../../css/choice.css" />
		<link rel="stylesheet" href="../../css/hui.css" />

		<script type="text/javascript" src="../../libs/vue.js"></script>
		<script type="text/javascript" src="../../js/jquery.1.9.1.min.js"></script>
		<script type="text/javascript" src="../../js/app/url.js"></script>
		<script type="text/javascript" src="../../js/mui.min.js"></script>

		<script type="text/javascript" src="../../libs/hui.js"></script>
		<script type="text/javascript" src="../../js/app/api.js?time=20181261"></script>
		<script type="text/javascript" src="../../js/control/pop.js"></script>
		<script type="text/javascript" src="../../js/md5.js"></script>
			<script type="text/javascript" src="../../js/app/ble.js"></script>



		
</head>
<body>
	<div id="wrapper">
<header class="f_l maxbox subhead">
  <a class="back" @click="back"><i class="iconfont">&#xe605;</i></a>
  <h1>巡检-连接设备</h1>
</header>
<section class="f_l maxbox unlock">
  <ul>
    <li>
      <b class="f_l gray">附近设备列表</b>
      <a class="f_r" @click="getBleList"><i class="iconfont orange">&#xe61a;</i></a>
    </li>
    <li v-for="(ble,index)  in bleList" >
      <p class="radio radio_success">
        <input name="choice1"   type="radio" value="option1">
        <label for="radio1">{{ble.name}}({{ble.mac}})</label>
      </p>
      <div class="state">
        <!--{{ble.rssi}}-->
        <button @click="ble.isConnected==1?disconnectBle(ble.mac,index) :connectBle(ble.mac,index)" class="hui-button hui-button-small search" v-text=" ble.isConnected==1?'断开连接':'连接'"></button>
      </div>
      
      	
      
    </li>
  
  </ul>
</section>


</div>

<script>
	
	
	
	
	var bleConnect;

		
		 			var BAdapter;

			mui.plusReady(function(){
				 var BluetoothAdapter = plus.android.importClass("android.bluetooth.BluetoothAdapter");
			     BAdapter = new BluetoothAdapter.getDefaultAdapter();
			    if (!BAdapter.isEnabled()) {
//			    	hui.toast("请开启蓝牙");
			        BAdapter.enable(); //启动蓝牙
			    }else{
//			        BAdapter.disable();
			    }
					bleConnect = plus.blecontroler;

						//扫描前初始化蓝牙
//						bleConnect.destory();
						var returnStr = bleConnect.init()
						
						vm.getBleList();

//					vm.getBleList();

			});
	
	
	var vm =new Vue({
		el:"#wrapper",
		data:{
			
				bleList: [],
				connectedDevice: null, //连接的设备
				notifyList: [], //通知列表
				Tid: "", //终端编号
		},
		mounted: function() {
			
			
		
		},
		
		methods:{
			
		

						
			goSetting:function(param){
				if(param == '1') {
//									hui.open("setting.html?time="+apiManage.getNow(), {}, true, {});

				var type = localStorage.getItem("type");
		          	hui.BackDo = function() {
						var current = plus.webview.currentWebview();
						var openCurrent = current.opener();
						if(openCurrent) {
							console.log("调用上一个页面刷新:" + openCurrent.id);
							openCurrent.evalJS("refresh()");
						}
						return true;
					}
				}else{
					
				}
				
			},
			back:function(){
				console.log("this.connectedDevice-"+this.connectedDevice);
				if(this.connectedDevice!=null){
					var readyBlockMac = this.connectedDevice.mac;
					bleConnect.disconnectBle(readyBlockMac);
				}
				
				bleConnect.destory();
				hui.back();
				
			}
			,
				getBleList: function() {
//					alert('22');
						if(!window.plus) {
							alert("请在H5+环境中使用!");
							return;
						}

	if(!BAdapter.isEnabled()){
							hui.toast("请开启蓝牙设置");
							return;
						}

						var _self = this;

						if(this.connectedDevice!=null){
							var readyBlockMac = this.connectedDevice.mac;
							bleConnect.disconnectBle(readyBlockMac);
						}
				

//						hui.loading("正在搜索蓝牙设备...");
						//3243
						var deviceName = ""; //指定蓝牙设备名
						vm.bleList = [];
						//开始搜索蓝牙设备
//						if(this.connectedDevice!=null){
//							_self.bleList = _self.bleList.concat(this.connectedDevice);
//						}
						bleConnect.scan(deviceName, function(sucess) {
							hui.closeLoading();
							console.log("搜索出来的-----"+sucess);
							var ret = JSON.parse(sucess);
//							if(ret.state)!=null){
//								return;
//							}
							
							if(ret.state == 0) {
								
								
//						if (ret.ble.name!=null){
								_self.bleList = _self.bleList.concat(ret.ble);
//						}
								
						
							} else {
								hui.closeLoading();
								console.log("搜索完成");
							}
						}, function(err) {
							hui.closeLoading();
//							alert(err);
							console.log(err);
						});

					},

					//连接设备
					connectBle: function(mac, index) {
						var _self = this;
						hui.loading("正在连接蓝牙设备...");
						bleConnect.connectBle(mac, function(ret) {
							console.log("连接蓝牙设备成功:" + ret);
							hui.closeLoading();
							hui.toast("连接蓝牙设备成功");

							
							setTimeout(function() {
								getTid();
							}, 250);

							_self.connectedDevice = _self.bleList[index];
							_self.$set(_self.bleList[index], "isConnected", 1);
						}, function(err) {
							
							hui.closeLoading();
							console.log(err);
							hui.toast("连接失败");
						});
					},

					disconnectBle: function(mac, index) {
						bleConnect.disconnectBle(mac);
						this.$set(this.bleList[index], "isConnected", 0);
						this.connectedDevice = null;
					},
		}
	});
	
	
	//获取终端编号
			function getTid() {
//				alert('getTid');
				bleConnect.writeData("5A1008FFFFFFFFFFFFFFFF", function(ret) {
					console.log("返回数据:" + ret);
//					var cell = JSON.parse(ret);
					if(ret.indexOf("state") != -1){
						return;
					}
					vm.Tid = ret.substring(6, 22);
					localStorage.setItem("zd_id",vm.Tid);
					vm.notifyList = vm.notifyList.concat("获取终端: " + ret);
					
					console.log("终端ID: "+vm.Tid);
					
					if(vm.Tid!=null&&vm.Tid!=""){
						setTimeout(function(){
						loadDetail(vm.Tid);
					},250);
					}
					
					
//					
//					@click="goSetting"

				}, function(err) {
					hui.closeLoading();
					
					hui.toast("无法获取终端ID，请在设备列表选择本公司的终端！");
					console.log(err);
				});
			}
			
			
			//终端详情
			function loadDetail(zdCode){
//				alert(zdCode);
				//var pid = cell.zdID;
	 	var username=	localStorage.getItem("username");
		var sec= localStorage.getItem("sec_pwd");
  	var time = apiManage.getNow();
  	var key = "loginName="+username+"&passWord="+sec+"&time="+time;
  	var paramKey=hex_md5(key);
  	var jsonParam = JSON.stringify({loginName:username,time:time,key:paramKey});
  	
     console.log("jsonParam:  "+jsonParam);

			hui.loading("");
				   var path = urlManager.terminalDetail()+"?terminalCode="+zdCode;
				   console.log("path:  "+path);
				  		$.ajax({
		         type: "GET",
		         url: path,
		         beforeSend: function(request) {
		            request.setRequestHeader("loginName",username);
		            request.setRequestHeader("time",time);
		            request.setRequestHeader("sign",paramKey);
		            request.setRequestHeader("Content-Type","application/text");
		
		         },
		         success: function(result) {
		         	hui.closeLoading();
		          	console.log("终端详情:"+JSON.stringify(result));
		          	
		          	if(result==""||result==null){
		          		hui.toast("获取终端失败");
		          		return;
		          	}
		          	var myCustID=  localStorage.getItem("companyId");
		          	myCustID = myCustID.trim();
		          	var zdCustId = result.jgId.cusId;
		          	zdCustId = zdCustId.trim();
		          	
		          	var type = localStorage.getItem("type");
		          	hui.BackDo = function() {
						var current = plus.webview.currentWebview();
						var openCurrent = current.opener();
						if(openCurrent) {
							console.log("调用上一个页面刷新:" + openCurrent.id);
							openCurrent.evalJS("refresh()");
						}
						return true;
					}
		          	
		          	
		          	
		          	if(zdCustId==myCustID){
		          			localStorage.setItem("Tid",vm.Tid);
		          			hui.Back();
		          	}
		          	else{
		          			 localStorage.setItem("Tid",vm.Tid);
		          			hui.Back();

		          	}
		          	
		          	console.log("我的客户ID "+myCustID +"-  终端的客户ID "+result.jgId.cusId);
			      hui.closeLoading();

									
									
									
						}		 
		             
		         
		     });
				  
			}

</script>
</body>
</html>